package com.ruoyi.framework.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.NameHelper;
import com.ruoyi.common.enums.DeleteFlag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private ISysUserService userService;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        NameHelper nameHelper = JSONUtil.toBean(username, NameHelper.class);
        String userName = nameHelper.getName();
        String loginType = nameHelper.getLoginType();
        SysUser user;
        if (StrUtil.equals(loginType, Constants.LOGIN_TYPE_APP)) {
            user = userService.selectUserByPhone(userName);
        } else {
            user = userService.selectUserByUserName(userName);
        }
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", userName);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (DeleteFlag.DELETE.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", userName);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", userName);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);

        return createLoginUser(user, loginType);
    }

    public UserDetails createLoginUser(SysUser user, String loginType) {
        if (StrUtil.equals(loginType, Constants.LOGIN_TYPE_APP)) {
            return new LoginUser(user.getUserId(), user.getDeptId(), user, null);
        } else {
            return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        }
    }
}
